class Scheduler {
  taskList: ((value?: unknown) => void)[];
  count: number;
  maxNum: number;
  /**
   *
   * @param {number} maxNum 最大可以同时执行的任务的数量
   */
  constructor(maxNum: number) {
    this.taskList = [];
    this.count = 0;
    this.maxNum = maxNum;
  }
  async add(promiseCreator: () => Promise<any>) {
    if (this.count >= this.maxNum) {
      await new Promise((resolve) => {
        this.taskList.push(resolve);
      });
    }
    this.count++;
    const result = await promiseCreator();
    this.count--;
    if (this.taskList.length > 0) {
      const next = this.taskList.shift();
      if (next) next();
    }
    return result;
  }
}
